const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const cors = require('cors');

const app = express();
const PORT = 3000;
const SECRET_KEY = 'your-secret-key-here';

// 中间件配置
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));

// 模拟用户数据库
const users = [
    {
        id: 1,
        username: 'user',
        password: '123456',
        role: 'USER'
    },
    {
        id: 2,
        username: 'admin',
        password: 'admin123',
        role: 'ADMIN'
    }
];

// 登录路由
app.post('/api/login', (req, res) => {
    const { username, password } = req.body;

    // 查找用户
    const user = users.find(u => u.username === username && u.password === password);

    if (!user) {
        return res.status(401).json({
            success: false,
            message: '用户名或密码错误'
        });
    }

    // 生成 JWT token
    const token = jwt.sign(
        { 
            id: user.id,
            username: user.username,
            role: user.role
        },
        SECRET_KEY,
        { expiresIn: '24h' }
    );

    // 返回用户信息和token
    res.json({
        success: true,
        token,
        userInfo: {
            id: user.id,
            username: user.username,
            role: user.role
        }
    });
});

// 验证token的中间件
const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
        return res.status(401).json({
            success: false,
            message: '未提供认证token'
        });
    }

    jwt.verify(token, SECRET_KEY, (err, user) => {
        if (err) {
            return res.status(403).json({
                success: false,
                message: 'token无效或已过期'
            });
        }
        req.user = user;
        next();
    });
};

// 受保护的路由示例
app.get('/api/protected', authenticateToken, (req, res) => {
    res.json({
        success: true,
        message: '认证成功',
        user: req.user
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
}); 